package com.biscuit.page.basicservice.design.flow_limit.strategy;

import org.springframework.beans.factory.InitializingBean;

/**
 * @author biscuit
 * @create 2024年07月29日 15:18
 */
public class TokenBucketFlowLimitHandlerStrategy implements FlowLimitHandlerStrategy {

    private int capacity;  // 令牌桶容量

    private long lastRefillTime;  // 上次令牌补充时间

    private int refillRate;  // 令牌生成速率（每秒生成的令牌数）

    @Override
    public void init() {
        this.capacity = 30;
        this.refillRate = 5;
        this.lastRefillTime = System.currentTimeMillis();
    }

    // 尝试获取令牌
    private synchronized boolean getToken() {
        // 计算从上次补充令牌到现在的时间间隔
        long currentTime = System.currentTimeMillis();
        long elapsedTime = currentTime - lastRefillTime;

        // 根据时间间隔补充令牌
        int tokensToAdd = (int) (elapsedTime * refillRate / 1000);
        int currentTokens = Math.min(capacity, tokensToAdd + capacity);

        // 如果有令牌可用，消耗一个令牌并返回 true，否则返回 false
        if (currentTokens > 0) {
            capacity--;
            lastRefillTime = currentTime;
            return true;
        }
        return false;
    }

    @Override
    public boolean attempt() {
        return getToken();
    }
}
